package com.karry.yl.web.elder;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.karry.commons.Constants;
import com.karry.commons.PDFGenerator;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.ObjectTransverter;
import com.karry.commons.util.TimeUtil;
import com.karry.commons.vo.JsonResponse;
import com.karry.commons.vo.LayTableResponse;
import com.karry.yl.domain.baseinfo.Organization;
import com.karry.yl.domain.elder.Elderly;
import com.karry.yl.domain.elder.ElderlyPath;
import com.karry.yl.domain.elder.Folk;
import com.karry.yl.domain.elder.Transefer;
import com.karry.yl.domain.healthdata.HealthData;
import com.karry.yl.domain.services.Meal;
import com.karry.yl.domain.services.Records;
import com.karry.yl.domain.system.*;
import com.karry.yl.service.baseinfo.OrganizationService;
import com.karry.yl.service.elder.ElderlyPathService;
import com.karry.yl.service.elder.ElderlyService;
import com.karry.yl.service.elder.TranseferService;
import com.karry.yl.service.healthdata.HealthDataService;
import com.karry.yl.service.services.MealService;
import com.karry.yl.service.services.RecordsService;
import com.karry.yl.service.system.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.ponly.fs.FileSystem;
import org.ponly.fs.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 老人档案Controller
 */

@Controller
@RequestMapping("/elderly")
public class ElderlyController extends SuperController {

    private static final Logger LOG = LoggerFactory.getLogger(ElderlyController.class);
    @Autowired
    private ElderlyService elderlyService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private TranseferService transeferService;
    @Autowired
    private HealthDataService healthDataService;
    @Autowired
    private RecordsService recordsService;

    @Autowired
    private MealService mealService;
    @Autowired
    private ProvinceService provinceService;
    @Autowired
    private CityService cityService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private TownService townService;
    @Autowired
    private VillageService villageService;
    @Autowired
    private FileSystem fs;
    @Autowired
    private ElderlyPathService elderlyPathService;

    @RequestMapping
    public String listUI() {
        return "elder/elderly/list";
    }

    @RequestMapping("/add")
    public String addUI(ModelMap map) {
        List<Province> provinces = provinceService.selectList(null);
        map.put("provinceList", provinces);
        return "elder/elderly/add";
    }

    @RequestMapping("edit")
    public String editUI(Long id, ModelMap map) {
        Elderly elderly = elderlyService.selectById(id);
        List<Folk> folks = elderlyService.selectFamilyList(elderly.getId());
        map.put("elderly", elderly);
        map.put("folks", folks);
        List<Province> provinces = provinceService.selectList(null);
        map.put("provinceList", provinces);
        List<ElderlyPath> elderlyPaths = elderlyPathService.selectList(new EntityWrapper<ElderlyPath>().eq("elderlyId", elderly.getId()).eq("deleted",false));
        map.put("elderlyPaths", elderlyPaths);
        if (!StringUtils.isEmpty(elderly.getProvinceCode()) && !StringUtils.isEmpty(elderly.getCityCode()) && !StringUtils.isEmpty(elderly.getAreaCode()) && !StringUtils.isEmpty(elderly.getTownCode())) {
            List<City> cityList = cityService.selectList(new EntityWrapper<City>().like("id", elderly.getProvinceCode().substring(0, 2), SqlLike.RIGHT));
            List<Area> areaList = areaService.selectList(new EntityWrapper<Area>().like("id", elderly.getCityCode().substring(0, 4), SqlLike.RIGHT));
            List<Town> townList = townService.selectList(new EntityWrapper<Town>().like("id", elderly.getAreaCode().substring(0, 6), SqlLike.RIGHT));
            List<Village> villageList = villageService.selectList(new EntityWrapper<Village>().like("id", elderly.getTownCode().substring(0, 9), SqlLike.RIGHT));
            map.put("cityList", cityList);
            map.put("areaList", areaList);
            map.put("townList", townList);
            map.put("villageList", villageList);
        }
        return "elder/elderly/editone";
    }

    @RequestMapping("/list")
    @ResponseBody
    public LayTableResponse listUI(int page, int limit, Integer healthCondition, Integer checkedIn, String code, String name, Integer mealStatus) {
        Wrapper<Elderly> elderlyWrapper = new EntityWrapper<Elderly>().eq("orgId", currentUser.getOrgId()).eq("deleted", false);
        if (null != healthCondition) {
            elderlyWrapper.eq("healthCondition", healthCondition);
        }
        if (null != checkedIn) {
            elderlyWrapper.eq("checkedIn", checkedIn);
        }
        if (!StringUtils.isEmpty(code)) {
            elderlyWrapper.like("code", code);
        }
        if (!StringUtils.isEmpty(name)) {
            elderlyWrapper.like("name", name);
        }

        if (null != mealStatus) {
            switch (mealStatus) {
                case 1: {
                    elderlyWrapper.isNull("mealId").or().lt("mealId", 0);
                }
                break;
                case 2: {
                    elderlyWrapper.gt("mealId", 0);
                }
                break;
                case 3: {
                    Calendar curr = Calendar.getInstance();
                    curr.add(Calendar.DAY_OF_MONTH, 3);
                    elderlyWrapper.gt("mealId", 0).le("mealEndTime", curr.getTime());
                }
                break;
                case 4: {
                    elderlyWrapper.gt("mealId", 0).lt("mealEndTime", new Date());
                }
                break;
            }

        }
        Page<Elderly> elderlyPage = elderlyService.selectPage(new Page<Elderly>(page, limit), elderlyWrapper.orderBy("createdTime", false));
        return new LayTableResponse(elderlyPage.getRecords(), elderlyPage.getTotal());
    }



    /**
     * 验证字段是否存在
     *
     * @param field
     * @param value
     * @return
     */
    @RequestMapping(path = "/exists")
    @ResponseBody
    public JsonResponse exists(String field, String value, Boolean all, Long id) {
        Wrapper<Elderly> elderlyWrapper = new EntityWrapper<Elderly>();
        if (null == all || !all) {
            elderlyWrapper.eq("orgId", currentUser.getOrgId());
        }
        elderlyWrapper.eq(field, value).eq("deleted", false);
        if (null != id) {
            elderlyWrapper.ne("id", id);
        }
        Elderly elderly = elderlyService.selectOne(elderlyWrapper);
        if (null != elderly) {
            return JsonResponse.success(true);
        }
        return JsonResponse.success(false);
    }

    /**
     * 转入档案页面
     *
     * @return
     */
    @RequestMapping("/transefer")
    public String transeferUI() {
        return "elder/elderly/transefer";
    }

    /**
     * 获取老人及其机构信息
     *
     * @return
     */
    @RequestMapping("/transefer/info")
    @ResponseBody
    public JsonResponse transeferInfo(String idNo) {
        Elderly elderly = elderlyService.selectOne(new EntityWrapper<Elderly>().eq("idNo", idNo));
        if (null != elderly) {
            if (elderly.getOrgId().equals(currOrganization.getId())) {
                return JsonResponse.fail("该老人档案已在当前机构！");
            }
            Organization organization = organizationService.selectById(elderly.getOrgId());
            elderly.setOrganization(organization);
        }
        return JsonResponse.success(elderly);
    }

    @RequestMapping("/transefer/save")
    @ResponseBody
    public JsonResponse transefer(Long elderlyId) {
        Elderly elderly = elderlyService.selectById(elderlyId);
        Transefer transefer = new Transefer();
        transefer.setElderlyId(elderly.getId());
        transefer.setElderlyName(elderly.getName());
        transefer.setElderlyIdNo(elderly.getIdNo());
        Organization fromOrg = organizationService.selectById(elderly.getOrgId());
        transefer.setFromId(fromOrg.getId());
        transefer.setFromName(fromOrg.getName());
        transefer.setToId(currOrganization.getId());
        transefer.setToName(currOrganization.getName());
        transefer.setStatus(Transefer.STATUS_DZ);
        transeferService.insert(transefer);
        return JsonResponse.success(elderly);
    }

    /**
     * 查看老人详细信息
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/info")
    public String info(Long id, ModelMap map) {
        Elderly elderly = elderlyService.selectById(id);
        List<Folk> folks = elderlyService.selectFamilyList(elderly.getId());
        map.put("elderly", elderly);
        map.put("folks", folks);
        //查询老人健康数据
        List<HealthData> healthDataList = healthDataService.selectByElderlyId(id);
        map.put("healthDataList", healthDataList);
        //查询老人服务记录
        Wrapper<Records> recordsWrapper = new EntityWrapper<Records>().eq("elderlyId", id).eq("deleted", false).orderBy("createdTime", false);
        List<Records> records = recordsService.selectList(recordsWrapper);
        map.put("records", records);
        return "elder/elderly/info";
    }


    /**
     * 绑定套餐页面
     *
     * @param map
     * @return
     */
    @RequestMapping("/ui/meal/bind")
    public String bindMealUI(Long elderlyId, ModelMap map) {
        List<Meal> mealList = mealService.selectAll(currentUser.getOrgId());
        map.put("mealList", mealList);
        Elderly elderly = elderlyService.selectById(elderlyId);
        map.put("elderly", elderly);
        boolean expire = false;
        if (null != elderly.getMealEndTime()) {
            long millis = elderly.getMealEndTime().getTime() - System.currentTimeMillis();
            expire = millis / (1000 * 60 * 60 * 24) <= Constants.meail_limit;
        }
        map.put("expire", expire);
        return "elder/elderly/mealBind";
    }


    /**
     * 绑定套餐
     *
     * @return
     */
    @RequestMapping("/meal/bind")
    public String bindMeal(Long elderlyId, Long tcId, String tcName) {
        elderlyService.bindMeal(elderlyId, tcId, tcName, currentUser.getId(), currOrganization.getName());
        return "redirect:/elderly";
    }

    /**
     * 套餐续费
     *
     * @return
     */
    @RequestMapping("/meal/xufei")
    public String xufei(Long elderlyId) {
        elderlyService.mealXufei(elderlyId, currentUser.getId(), currOrganization.getName());
        return "redirect:/elderly";
    }


    /**
     * 批量续费
     *
     * @return
     */
    @RequestMapping("/meal/plxufei")
    public String plxufei(Long[] elderlyId) {
        elderlyService.mealXufei(elderlyId, currentUser.getId(), currOrganization.getName());
        return "redirect:/elderly";
    }



    /**
     * 获取老人信息
     *
     * @return
     */
    @RequestMapping("/selectById")
    @ResponseBody
    public JsonResponse selectById(Long id) {
        Elderly elderly = elderlyService.selectOne(new EntityWrapper<Elderly>().eq("id", id));
        return JsonResponse.success(elderly);
    }
    /**
     * 获取老人绑定套餐信息
     *
     * @return
     */
    @RequestMapping("/selectMeals")
    @ResponseBody
    public JsonResponse selectMeals(Long mealId) {
        int n= elderlyService.selectCount(new EntityWrapper<Elderly>().eq("mealId", mealId));
        if(n>0){
            return JsonResponse.fail("err");
        }
        return JsonResponse.success("suss");
    }
}
